import { createStore } from 'vuex'

export default createStore({
    state: {
        cartItems: []
    },
    mutations: {
        addToCart(state, product) {
            const existing = state.cartItems.find(item => item.id === product.id && item.spec === product.spec)
            if (existing) {
                existing.quantity += product.quantity
            } else {
                state.cartItems.push({ ...product })
            }
        },
        removeFromCart(state, id) {
            state.cartItems = state.cartItems.filter(item => item.id !== id)
        },
        updateCartItem(state, payload) {
            const item = state.cartItems.find(item => item.id === payload.id)
            if (item) {
                item.quantity = payload.quantity
            }
        },
        clearCart(state) {
            state.cartItems = []
        }
    },
    getters: {
        cartCount(state) {
            return state.cartItems.reduce((count, item) => count + item.quantity, 0)
        }
    }
})